#include "chessboardwidget.h"
#include <QMessageBox>
#include <QStack>

ChessBoardWidget::ChessBoardWidget(QWidget* parent)
    : QWidget(parent)
    , m_isBlackTurn(true)
    , m_gameOver(false)
    , m_showHover(false)
    , m_gameTime(0)
    , m_lastMoveRow(-1)
    , m_lastMoveCol(-1)
    , m_soundEffect(new QSoundEffect(this))
{
    setMouseTracking(true);
    setMinimumSize(100, 100);

    // 创建计时器
    m_timer = new QTimer(this);
    connect(m_timer, &QTimer::timeout, this, &ChessBoardWidget::updateTimer);

    //初始化音频
    m_soundEffect->setVolume(1.0f);
    initGame();
}

ChessBoardWidget::~ChessBoardWidget()
{
    if (m_timer && m_timer->isActive()) {
        m_timer->stop();
    }
}

void ChessBoardWidget::initGame()
{
    // 初始化棋盘
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            m_board[i][j] = 0;
        }
    }

    m_isBlackTurn = true;
    m_lastMoveRow = -1;
    m_lastMoveCol = -1;
    m_gameOver = false;
    m_gameTime = 0;
    m_showHover = false;
    m_moveHistory.clear();

    m_timer->start(1000);
    emit gameStateChanged(m_isBlackTurn);
    emit gameTimeUpdated(m_gameTime);

    update();
}

void ChessBoardWidget::restartGame()
{
    initGame();
}

bool ChessBoardWidget::regretMove()
{
    if (m_moveHistory.isEmpty() || m_gameOver) {
        return false;
    }

    QPoint lastMove = m_moveHistory.pop();
    m_board[lastMove.y()][lastMove.x()] = 0;

    // 如果还有上一步，更新最后落子位置
    if (!m_moveHistory.isEmpty()) {
        QPoint prevMove = m_moveHistory.top();
        m_lastMoveRow = prevMove.y();
        m_lastMoveCol = prevMove.x();
    }
    else {
        m_lastMoveRow = -1;
        m_lastMoveCol = -1;
    }

    switchPlayer();
    update();
    return true;
}

void ChessBoardWidget::setAIMode(bool enabled)
{
    // AI模式实现留空，后续扩展
    Q_UNUSED(enabled);
}

void ChessBoardWidget::paintEvent(QPaintEvent* event)
{
    Q_UNUSED(event);

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    calculateBoardSize();
    drawBoard(painter);
    drawPieces(painter);
    drawLastMoveMarker(painter);

    if (m_showHover && !m_gameOver) {
        drawHoverPiece(painter);
    }
}

void ChessBoardWidget::calculateBoardSize()
{
    int availableSize = qMin(width(), height()) - CELL_MARGIN * 2;
    m_cellSize = availableSize / BOARD_SIZE;
    m_boardTopLeft = QPoint(
        (width() - m_cellSize * BOARD_SIZE) / 2,
        (height() - m_cellSize * BOARD_SIZE) / 2
    );
}

void ChessBoardWidget::drawBoard(QPainter& painter)
{
    // 绘制棋盘背景
    painter.fillRect(m_boardTopLeft.x() - CELL_MARGIN,
        m_boardTopLeft.y() - CELL_MARGIN,
        m_cellSize * BOARD_SIZE + CELL_MARGIN * 2,
        m_cellSize * BOARD_SIZE + CELL_MARGIN * 2,
        QColor(210, 180, 140));

    // 绘制棋盘线
    painter.setPen(QPen(Qt::black, 1.5));

    for (int i = 0; i < BOARD_SIZE; ++i) {
        // 横线
        int y = m_boardTopLeft.y() + i * m_cellSize;
        painter.drawLine(m_boardTopLeft.x(), y,
            m_boardTopLeft.x() + (BOARD_SIZE - 1) * m_cellSize, y);

        // 竖线
        int x = m_boardTopLeft.x() + i * m_cellSize;
        painter.drawLine(x, m_boardTopLeft.y(),
            x, m_boardTopLeft.y() + (BOARD_SIZE - 1) * m_cellSize);
    }

    // 绘制星位
    painter.setBrush(Qt::black);
    int starPoints[5][2] = {
        {3, 3}, {3, 11}, {7, 7}, {11, 3}, {11, 11}
    };

    for (auto& point : starPoints) {
        int x = m_boardTopLeft.x() + point[0] * m_cellSize;
        int y = m_boardTopLeft.y() + point[1] * m_cellSize;
        painter.drawEllipse(QPoint(x, y), 4, 4);
    }
}

void ChessBoardWidget::drawPieces(QPainter& painter)
{
    for (int i = 0; i < BOARD_SIZE; ++i) {
        for (int j = 0; j < BOARD_SIZE; ++j) {
            if (m_board[i][j] != 0) {
                int x = m_boardTopLeft.x() + j * m_cellSize;
                int y = m_boardTopLeft.y() + i * m_cellSize;
                QPoint center(x, y);

                QRadialGradient gradient(center, m_cellSize * 0.45);

                if (m_board[i][j] == 1) { // 黑棋
                    gradient.setColorAt(0, QColor(100, 100, 100));
                    gradient.setColorAt(1, Qt::black);
                }
                else { // 白棋
                    gradient.setColorAt(0, Qt::white);
                    gradient.setColorAt(1, QColor(200, 200, 200));
                }
                painter.setBrush(gradient);
                painter.setPen(QPen(Qt::black, 1));
                painter.drawEllipse(QPointF(center), m_cellSize * 0.4, m_cellSize * 0.4);
            }
        }
    }
}

void ChessBoardWidget::drawLastMoveMarker(QPainter& painter)
{
    if (m_lastMoveRow != -1 && m_lastMoveCol != -1) {
        int x = m_boardTopLeft.x() + m_lastMoveCol * m_cellSize;
        int y = m_boardTopLeft.y() + m_lastMoveRow * m_cellSize;

        painter.setPen(QPen(Qt::red, 2));
        painter.drawEllipse(QPoint(x, y), 3, 3);
    }
}

void ChessBoardWidget::drawHoverPiece(QPainter& painter)
{
    int row = m_hoverPos.y();
    int col = m_hoverPos.x();

    if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE &&
        m_board[row][col] == 0) {

        int x = m_boardTopLeft.x() + col * m_cellSize;
        int y = m_boardTopLeft.y() + row * m_cellSize;
        QPoint center(x, y);

        // 半透明悬停效果
        QColor hoverColor = m_isBlackTurn ? Qt::black : Qt::white;
        hoverColor.setAlpha(100);

        painter.setBrush(hoverColor);
        painter.setPen(QPen(Qt::gray, 1));
        painter.drawEllipse(QPointF(center), m_cellSize * 0.35, m_cellSize * 0.35);
    }
}

void ChessBoardWidget::mouseMoveEvent(QMouseEvent* event)
{
    if (m_gameOver) return;

    QPoint boardPos = windowToBoard(event->pos());
    if (boardPos != m_hoverPos) {
        m_hoverPos = boardPos;
        m_showHover = (boardPos.x() >= 0 && boardPos.x() < BOARD_SIZE &&
            boardPos.y() >= 0 && boardPos.y() < BOARD_SIZE &&
            m_board[boardPos.y()][boardPos.x()] == 0);
        update();
    }
}

void ChessBoardWidget::mousePressEvent(QMouseEvent* event)
{
    if (m_gameOver) return;

    if (event->button() == Qt::LeftButton) {
        QPoint boardPos = windowToBoard(event->pos());
        int row = boardPos.y();
        int col = boardPos.x();
       
        if (row >= 0 && row < BOARD_SIZE && col >= 0 && col < BOARD_SIZE) {
            if (placePiece(row, col)) {
                m_showHover = false;
            }
        }
    }
}

void ChessBoardWidget::resizeEvent(QResizeEvent* event)
{
    QWidget::resizeEvent(event);
    calculateBoardSize();
    update();
}

void ChessBoardWidget::leaveEvent(QEvent* event)
{
    Q_UNUSED(event);
    m_showHover = false;
    update();
}

QPoint ChessBoardWidget::windowToBoard(const QPoint& windowPos)
{
    int col = qRound((windowPos.x() - m_boardTopLeft.x()) / (float)m_cellSize);
    int row = qRound((windowPos.y() - m_boardTopLeft.y()) / (float)m_cellSize);
    return QPoint(col, row);
}

bool ChessBoardWidget::placePiece(int row, int col)
{
    if (m_board[row][col] != 0) return false;

    m_board[row][col] = m_isBlackTurn ? 1 : 2;
    m_moveHistory.push(QPoint(col, row));
    m_lastMoveRow = row;
    m_lastMoveCol = col;

    //播放音效落子

  // 使用 WAV 格式文件
    m_soundEffect->setSource(QUrl::fromLocalFile("C:\\Users\\xiejun\\Desktop\\qplayter\\qGameVideo\\resource\\down7.wav"));
    if (m_soundEffect->status() == QSoundEffect::Ready) {
        m_soundEffect->play();
    }
  






    if (checkWin(row, col)) {
        m_gameOver = true;
        m_timer->stop();
        emit gameOver(m_isBlackTurn ? 1 : 2);
    }
    else {
        switchPlayer();
    }

    update();
    return true;
}

bool ChessBoardWidget::checkWin(int row, int col)
{
    int directions[4][2] = { {1,0}, {0,1}, {1,1}, {1,-1} };

    for (auto& dir : directions) {
        if (checkFiveInLine(row, col, dir[0], dir[1])) {
            return true;
        }
    }

    return false;
}

bool ChessBoardWidget::checkFiveInLine(int row, int col, int dr, int dc)
{
    int player = m_board[row][col];
    int count = 1;

    // 正向检查
    for (int i = 1; i <= 4; i++) {
        int r = row + dr * i;
        int c = col + dc * i;
        if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE &&
            m_board[r][c] == player) {
            count++;
        }
        else {
            break;
        }
    }

    // 反向检查
    for (int i = 1; i <= 4; i++) {
        int r = row - dr * i;
        int c = col - dc * i;
        if (r >= 0 && r < BOARD_SIZE && c >= 0 && c < BOARD_SIZE &&
            m_board[r][c] == player) {
            count++;
        }
        else {
            break;
        }
    }

    return count >= 5;
}

void ChessBoardWidget::switchPlayer()
{
    m_isBlackTurn = !m_isBlackTurn;
    emit gameStateChanged(m_isBlackTurn);
}

void ChessBoardWidget::updateTimer()
{
    if (!m_gameOver) {
        m_gameTime++;
        emit gameTimeUpdated(m_gameTime);
    }
}
